using SimpleJSON;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class SuperXPHelper : NodeHelper
    {
        public BindDataType dataType = BindDataType.Int;
        [SelectRef(UIKey.ATTR_KEY)] public string xpKey;
        [SelectRef(UIKey.ATTR_KEY)] public string levelKey;
        [SelectRef(UIKey.DATA_KEY)] public SelectKey attrKey;
        [SelectRef(UIKey.DATA_KEY)] public SelectKey xpInfoKey;
        public string format;
        public Text Text;
        public TextMeshProUGUI TextPro;
        public Image Image;
        public Slider Slider;

        protected override BindDataType bindDataType => dataType;

        protected override void BindData(JSONObject obj)
        {
            SetData(obj[levelKey].AsInt);
        }

        protected override void BindData(int level)
        {
            var attrData = attrKey.Get(_data).AsObject;
            var xpValue = attrData[xpKey].AsInt;
            var totalList = xpInfoKey.Get(_data).AsArray;
            var overValue = level - 2 < 0 ? 0 : totalList[level - 2].AsInt;
            var end = level - 1 >= totalList.Count;
            var totalxpValue = end ? totalList[totalList.Count - 1].AsInt : totalList[level - 1].AsInt;

            // Debug.LogErrorFormat("{0} {1} {2} {3}", xpValue, overValue, totalxpValue, overValue);
            var tmp = new object[2] { xpValue - overValue, totalxpValue - overValue };
            if (Text != null) Text.text = string.Format(format, tmp);
            if (TextPro != null) TextPro.text = string.Format(format, tmp);
            if (Image != null)
                Image.fillAmount = totalxpValue == 0 ? 0 : (xpValue - overValue) / (float)(totalxpValue - overValue);
            if (Slider != null)
                Slider.value = totalxpValue == 0 ? 0 : (xpValue - overValue) / (float)(totalxpValue - overValue);
        }

        private void SetText(string t)
        {
            Text.text = t;
        }
    }
}